import { app, shell, BrowserWindow, nativeImage } from 'electron'
import { join } from 'path'
import { is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
import appIcon from '../../build/icon.png?asset'

// 子窗口
export default () => {
    // 窗口数组，管理所有窗口
    let childWindows: any[] = []

    // 主窗口
    const mainWindow = () => {
        const mainWindow = new BrowserWindow({
            width: 600,
            height: 500,
            show: false,
            autoHideMenuBar: true,
            title: 'template',
            ...(process.platform === 'linux' ? { icon } : {}),
            webPreferences: {
                // 预加载脚本
                preload: join(__dirname, '../preload/index.js'),
                nodeIntegration: true,
                contextIsolation: false,
                webSecurity: true, // 关闭安全策略 ，允许跨域加载
                allowRunningInsecureContent: false, // 允许加载本地资源(http协议)
                sandbox: false
            },
            icon: nativeImage.createFromPath(appIcon)
        })
        mainWindow.on('ready-to-show', () => {
            mainWindow.show()
        })

        mainWindow.webContents.setWindowOpenHandler((details) => {
            shell.openExternal(details.url)
            return { action: 'deny' }
        })
        // 加载页面
        if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
            mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
        } else {
            mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
        }
        // 窗口关闭事件
        mainWindow.on('close', () => {
            childWindows = childWindows.filter(childWindow => !childWindow.isDestroyed())
            childWindows.forEach(childWindow => childWindow.close())
            app.quit()
        })
    }

    const childWindow = (param: any) => {
        const exits = childWindows.find(childWindow => childWindow["name"] === param.name && !childWindow.isDestroyed())
        // 判断该窗口是否存在，如果存在则关闭
        // if (exits) {
        //   exits.close()
        //   childWindows = childWindows.filter(childWindow => childWindow["name"] !== name)
        // }

        // 如果窗口存在则实现窗口最小化的切换
        if (exits) {
            if (exits.isMinimized()) {
                exits.restore()
            } else {
                exits.minimize()
            }
            return
        }

        const View = new BrowserWindow({
            width: param.width ? param.width : 600,
            height: param.height ? param.height : 500,
            show: true,
            // 隐藏默认菜单
            autoHideMenuBar: true,
            // 设置标题
            title: param.title,
            // 窗口置顶
            alwaysOnTop: false,
            webPreferences: {
                // 预加载脚本
                preload: join(__dirname, '../preload/index.js'),
                nodeIntegration: true,
                contextIsolation: false,
                webSecurity: true
            },
            icon: nativeImage.createFromPath(appIcon)
        })
        View["name"] = param.name
        // 加载页面
        if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
            View.loadURL(`http://localhost:5173/#${param.url}`)
        } else {
            View.loadFile(join(__dirname, '../renderer/index.html'), {
                hash: param.url
            })
        }
        childWindows.push(View)
    }

    return {
        mainWindow,
        childWindow
    }
}